package com.yx.musicplayer.service;

import android.Manifest;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.annotation.Nullable;
import android.support.v4.media.session.MediaSessionCompat;
import android.support.v7.app.NotificationCompat;

import com.yx.baselibrary.base.BaseLibraryApplication;
import com.yx.baselibrary.utils.SPUtil;
import com.yx.musicplayer.R;
import com.yx.musicplayer.aidl.IMusicAidlInterface;
import com.yx.musicplayer.constant.SPConstant;
import com.yx.musicplayer.greendao.Song;
import com.yx.musicplayer.ui.activity.MainActivity;
import com.yx.musicplayer.util.MusicPlayer;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName MusicPlayerService
 * @Description 音乐播放service
 * Created by yx on 2017/10/31 0031.
 */

public class MusicPlayerService extends Service {
    private Notification notification;
    private android.support.v4.app.NotificationCompat.Builder builder;
    private MediaSessionCompat mSession;
    MusicPlayer musicPlayer;
    private ServiceBinder mBinder = new ServiceBinder(this);
    private int curPosition;
    private List<Song> palyList = new ArrayList<>();

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        musicPlayer = new MusicPlayer(this);

        reloadQueueAfterPermissionCheck();
        simpleNotify();

    }

    @Override
    public boolean onUnbind(Intent intent) {
        saveQueue();
        return true;
    }


    /**
     * 检测读写权限
     */
    private void reloadQueueAfterPermissionCheck() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (PackageManager.PERMISSION_GRANTED == BaseLibraryApplication.getAppContext().checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE)) {
                reloadQueue();
            }

        } else {
            reloadQueue();
        }
    }


    /**
     * 获取最近播放列表
     */
    private void reloadQueue() {
        palyList = SPUtil.getHistoryData(Song.class, SPConstant.LAST_SONGS);
        curPosition = SPUtil.getInt(SPConstant.LAST_POSITION, 0);
    }

    /**
     * 保存最近播放列表
     */
    private void saveQueue() {
        SPUtil.saveData(Song.class, SPConstant.LAST_SONGS);
        SPUtil.putInt(SPConstant.LAST_POSITION, curPosition);
    }


    public final static class ServiceBinder extends IMusicAidlInterface.Stub {
        private WeakReference<MusicPlayerService> serviceWeakReference;

        public ServiceBinder(MusicPlayerService musicPlayerService) {
            serviceWeakReference = new WeakReference<>(musicPlayerService);
        }

        @Override
        public void openFile(String path) {

        }

        @Override
        public void play() {
            serviceWeakReference.get().play();
//            ToastUtil.showShort("开始播放");
        }

        @Override
        public void stop() {
            serviceWeakReference.get().stop();
//            ToastUtil.showShort("暂停播放");
        }

        @Override
        public void pause() {

        }

        @Override
        public boolean isPlaying() throws RemoteException {
            return false;
        }
    }

    /**
     * 停止播放
     */
    private void stop() {

    }

    /**
     * 播放音乐
     */
    private void play() {
        musicPlayer.setDataSource(palyList.get(curPosition).getPath());
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
//        if (musicPlayer.isPlaying()){
//            musicPlayer.stop();
//            musicPlayer.release();
//        }

    }

    private void simpleNotify() {
        //为了版本兼容  选择V7包下的NotificationCompat进行构造
        if (builder == null) {
            builder = new NotificationCompat.Builder(this);
            //Ticker是状态栏显示的提示
            //第一行内容  通常作为通知栏标题
            builder.setContentTitle("星音乐");
            //第二行内容 通常是通知正文
            builder.setContentText("让音乐快乐你的生活~");
            //第三行内容 通常是内容摘要什么的 在低版本机器上不一定显示
//            builder.setSubText("大众生活正在后台运行！");
            //ContentInfo 在通知的右侧 时间的下面 用来展示一些其他信息
            //builder.setContentInfo("2");
            //number设计用来显示同种通知的数量和ContentInfo的位置一样，如果设置了ContentInfo则number会被隐藏
            //可以点击通知栏的删除按钮删除
            builder.setAutoCancel(true);
            //系统状态栏显示的小图标
            builder.mLargeIcon = BitmapFactory.decodeResource(getResources(), R.drawable.vector_drawable_music);
            builder.setSmallIcon(R.drawable.vector_drawable_music);
            //下拉显示的大图标
            //点击跳转的intent
            Intent intent = new Intent(this, MainActivity.class);
            intent.putExtra("from", "AutoOpenDoorService");
            PendingIntent pi = PendingIntent.getActivity(this, 0, intent, 0);
            builder.setContentIntent(pi);
            //通知默认的声音 震动 呼吸灯
            builder.setDefaults(NotificationCompat.DEFAULT_LIGHTS);
            builder.addAction(R.drawable.vector_drawable_pre_white,
                    "",
                    null);
            builder.addAction(R.drawable.vector_drawable_stop_white,
                    "",
                    null);
            builder.addAction(R.drawable.vector_drawable_next_white,
                    "",
                    null);

            mSession = new MediaSessionCompat(this, "Listener");
            mSession.setFlags(MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);
            builder.setVisibility(Notification.VISIBILITY_PUBLIC);
            NotificationCompat.MediaStyle style = new NotificationCompat.MediaStyle()
                    .setMediaSession(mSession.getSessionToken())
                    .setShowActionsInCompactView(0, 1, 2, 3);
            builder.setStyle(style);
            notification = builder.build();

            startForeground(1, notification);
        }
    }
}
